# -*- coding: utf-8 -*-
# created on 2017/01/16

from sympy import sympify
from mathsolver.functions.base import BaseFunction, BaseFunc, new_latex
from mathsolver.functions.hanshu.helper import check_inter
from mathsolver.functions.hanshu.zhouqi import is_fxplusa, is_fxplus_a, has_f
from mathsolver.functions.sympy_utils import get_all_child


def guanxishi1(left, right):
    """hs069.f(x+T)=Af(x)推出解析式关系"""
    dt = is_fxplusa(left)
    da = right.args[0]
    rhs = sympify('{A}**(-n)*f(x + n*{T})'.format(A=da, T=dt))
    st = "已知函数等式关系，则 f(x) = %s" % new_latex(rhs)
    return rhs, dt, st


def guanxishi2(left, right):
    """hs070.f(x+T)=f(x)+b推出解析式关系"""
    dt = is_fxplusa(left)
    b = is_fxplus_a(right)
    rhs = sympify('f(x + n*{T}) - {b}*n'.format(b=b, T=dt))
    st = "已知函数等式关系，则 f(x) = %s" % new_latex(rhs)
    return rhs, dt, st


def qujianguanxi_qiu_n(dt, inter, q_inter):
    """ step2 -> step5, x ∈ q_inter, 求 n 使得 x+2*n ∈ inter
    """

    low, low2 = inter._inf, q_inter._inf
    n = (low - low2) / dt
    step = "当 x ∈ %s 时，令 n = %s， 则 x + %s ∈ %s " % (q_inter, n, dt * n, inter)
    return n, step


class DengShiQiuJieXiShi(BaseFunction):
    """f(x)=Af(x+T)+b型求函数的解析式"""

    def solver(self, *args):
        funceq, inter, func, q_inter = args[0], check_inter(args[1]), args[2], check_inter(args[3])
        left, right = sympify(funceq.value)
        expr, var = func.expression, func.var

        # 判断等式类型
        if is_fxplus_a(right):
            new_expr, dt, st = guanxishi2(left, right)
        else:
            new_expr, dt, st = guanxishi1(left, right)

        self.steps.append(["", st])

        # x ∈ q_inter, 求 n 使得 x+2*n ∈ inter
        n, st = qujianguanxi_qiu_n(dt, inter, q_inter)
        self.steps.append(["", st])

        # 代入求值
        new_expr = new_expr.subs(sympify('n'), n)
        fx = get_all_child(new_expr, has_f)[0]
        inner_fx = fx.args[0]
        res = new_expr.subs(fx, expr.subs(var, inner_fx))
        self.steps.append(["", "将 n = %s 代入得 f(x) = %s = %s" % (n, new_expr, res)])

        self.output.append(BaseFunc({"var": var, "name": func.name, "type": "", "expression": res}))
        self.label.add("f(x)=Af(x+T)+b型求函数的解析式")
        return self


if __name__ == '__main__':
    pass
